/*
 * @Description: 数据请求封装
 * @Author: 谢涛
 * @Date: 2019-07-10 15:22:14
 * @LastEditTime: 2024-11-12 16:49:54
 * @LastEditors: 郑祥
 */

import axios from "axios";
import { message } from "antd";

axios.defaults.baseURL = '/api/';
//全局的 axios 默认值
let userInfo = "";
if (sessionStorage.getItem("userInfo") !== "") {
	userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
	axios.defaults.headers.common["Auth-Token"] =
		userInfo === null ? "" : userInfo.token;
}

//请求类型
axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";

//各种请求头
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.put["Content-Type"] = "application/json";
axios.defaults.headers.get["Content-Type"] = "application/json";
axios.defaults.headers.delete["Content-Type"] = "application/json";

//配置超时时间
axios.defaults.timeout = 20000;

// 添加一个请求拦截器
axios.interceptors.request.use(
	(config) => {
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// 添加一个响应拦截器
axios.interceptors.response.use(
	(res) => {
		if (res.data !== null) {
			return res.data;
		}
	},
	(err) => {
		if (err.response) {
			if (err.response.status <= 504 && err.response.status >= 500) {
				message.error("服务器错误，可尝试刷新页面，若无效请联系管理员");
			} else if (err.response.status >= 400 && err.response.status < 422) {
				if (err.response.status === 401) {
					window.location.pathname = "/login";
					sessionStorage.clear();
				} else {
					message.error("代码出错，可尝试刷新页面，若无效请联系管理员");
				}
			}
		} else {
			// message.error('服务器连接超时，可尝试刷新页面，若无效请联系管理员')
			// setTimeout(() => {
			//     window.location.pathname = '/login'
			// },3000)
		}
		return Promise.reject(err);
	}
);
export const baseURL = axios.defaults.baseURL;
export default axios;
